package com.sk.bilibili.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import com.sk.bilibili.bean.Skin;
import com.sk.bilibili.mapper.SkinMapper;

/**
 * @author 邵康
 * @date 2021/12/06 11:46
 */
@Service
public class SkinService extends ServiceImpl<SkinMapper, Skin> {

    @Autowired
    private MinioService minioService;
    private static final String URL_PATH = "skin/url/%s.jpg";
    private static final Pattern URL_PATTERN = Pattern.compile("/(skin/url/.*jpg)");
    private static final String SMALLURL_PATH = "skin/smallUrl/%s.jpg";
    private static final Pattern SMALLURL_PATTERN = Pattern.compile("/(skin/smallUrl/.*jpg)");

    public R<Void> add(Skin skin) {
        skin.setUrl(minioService.add(skin.getUrlFile(), URL_PATH));
        skin.setSmallUrl(minioService.add(skin.getSmallUrlFile(),SMALLURL_PATH));
        save(skin);
        return R.success();
    }

    public R<Void> delete(Integer id) {
        Skin temp = getById(id);
        minioService.delete(temp.getUrl(), URL_PATTERN);
        minioService.delete(temp.getSmallUrl(), SMALLURL_PATTERN);
        removeById(id);
        return R.success();
    }

    public R<Void> update(Skin skin) {
        Skin temp = getById(skin.getId());
        String url = minioService.update(URL_PATH, URL_PATTERN, temp.getUrl(), skin.getUrlFile());
        skin.setUrl(url);
        String smallUrl = minioService.update(SMALLURL_PATH, SMALLURL_PATTERN, temp.getSmallUrl(), skin.getSmallUrlFile());
        skin.setSmallUrl(smallUrl);
        updateById(skin);
        return R.success();
    }

    public R<IPage<Skin>> page(Integer page, Integer size) {
        return R.success(page(new Page<>(page, size), null));
    }

    public R<List<Skin>> getAll() {
        List<Skin> res=baseMapper.getAll(BSessionUtils.getMemberId());
        return R.success(res);
    }

}
